<script setup lang="ts">
import {ref, onMounted, reactive, computed, nextTick, watch} from 'vue';
import { NextLoading } from '/@/utils/loading';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import { useRoute, useRouter } from 'vue-router';
import { useLoginApi } from '/@/api/login';

// 定义变量内容
const route = useRoute();
const router = useRouter()

// 点击自动登录
const isAutomatic = ref(false)
const automaticChange = (event: any) => {
	isAutomatic.value = event;
}

const wechatLogin = () => {
	nextTick(async () => {
		//调用后台接口获取重定向地址，因人而异
		const response = await useLoginApi().getLoginWechatQrcode({});
		new WxLogin({
			self_redirect: false,
			id: "ER_code", //放置二维码的容器ID
			appid: response.data.appid,
			scope: "snsapi_login",
			redirect_uri: encodeURIComponent(response.data.redirectUrl), //编码重定向地址
			state: response.data.state,
			href: "data:text/css;base64,LndlYl9xcmNvZGVfdHlwZV9pZnJhbWUge3Bvc2l0aW9uOiBhYnNvbHV0ZTtsZWZ0OiAxNiU7Ym90dG9tOiAtOCU7fQouaW1wb3dlckJveCAucXJjb2RlIHt3aWR0aDogMjUwcHg7fQouaW1wb3dlckJveCAudGl0bGUge2Rpc3BsYXk6IG5vbmU7fQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIwMHB4O30KLnN0YXR1c19pY29uIHtkaXNwbGF5OiBub25lfQouaW1wb3dlckJveCAuc3RhdHVzIHt0ZXh0LWFsaWduOiBjZW50ZXI7fQ=="
		});
	})
}

// 处理扫码回调
const handleLoginCallback = async (code, state) => {
	try {
		const response = await useLoginApi().getLoginWechat({ code, state });
		// 登录成功
		if (response.code === 200) {
			Session.set('token', response.data.token);
			// 登录成功，跳到转首页
			signInSuccess(response.message);
		} else {
			// 登录失败，跳转到登录页
			await router.push('/login');
		}
	} catch (error) {
		// 登录失败，跳转到登录页
		ElMessage.error('登录失败，请重试');
		await router.push('/login');
	}
};

// 登录成功后的跳转
const signInSuccess = (message: string) => {
	// 登录成功，跳到转首页
	// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
	if (route.query?.redirect) {
		router.push({
			path: route.query?.redirect,
			query: Object.keys(route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
		});
	} else {
		router.push('/');
	}
	// 登录成功提示
	ElMessage.success(message);
	// 添加 loading，防止第一次进入界面时出现短暂空白
	NextLoading.start();
};

// 初始化
onMounted(() => {
	const script = document.createElement('script');
	script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
	document.body.appendChild(script);
	wechatLogin();

	watch(() => route.query, async (newValue) => {
		if (newValue?.code && newValue?.state) {
			// 扫码回调，处理登录
			await handleLoginCallback(newValue?.code, newValue?.state);
		}
	})
})
</script>

<template>
	<div class="flex-items-center wechat-title">
		<el-image src="https://ouan-retail.oss-cn-shenzhen.aliyuncs.com/web/login/%E5%BE%AE%E4%BF%A1.png"></el-image>
		<span>微信扫码登录</span>
	</div>
	<div id="ER_code"></div>
<!--	<div class="flex-around">-->
<!--		<el-checkbox v-model="isAutomatic" @change="automaticChange">-->
<!--			<template v-slot:default>-->
<!--				<p style="font-size: 14px;color: #666666;">下次自动登录</p>-->
<!--			</template>-->
<!--		</el-checkbox>-->
<!--	</div>-->
</template>

<style lang="scss">
.wechat-title {
	justify-content: center;
	font-size: 18px;
	color: #222222;

	img {
		width: 22px;
		height: 22px;
		margin-right: 10px;
	}
}
</style>